//
//  ViewController.swift
//  swift项目
//
//  Created by 龚昕炜 on 16/7/26.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {
    
    var list: [Person]?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.redColor()
        
        self.tableView.rowHeight = 100
        
//        self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
        
        /** 回调block */
        let closure = { (person: [Person]) ->() in
            
            self.list = person
            
            self.tableView.reloadData()
        }
        
        loadData(closure)
    }
    
    
}

extension ViewController
{
    func loadData(finish: (person: [Person])->())
    {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            
            NSThread.sleepForTimeInterval(2.0)
            
            var array: [Person] = [Person]()
            
            for i in 0..<50
            {
                let name = "IOS\(i)"
                
                let age = random() % 80
                
                let dict: [String: AnyObject] = ["name": name, "age": age]
                
                let person = Person(dict: dict)
//                print("\(age)")
                array.append(person)
            }
            
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                finish(person: array)
            }
        }
        
    }
}

extension ViewController
{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = (tableView.dequeueReusableCellWithIdentifier("Cell")) ?? UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
        
//        if (cell == nil) {
//            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
//        }
        
        let person = self.list![indexPath.row]
        
        cell.textLabel!.text = person.name
        
//        print("\(String(person.age))")
        cell.detailTextLabel!.text = String(person.age)
        
        
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let detailVC = DetailViewController()
        
        detailVC.closure = {
            self.tableView.reloadData()
        }
        
        detailVC.model = self.list?[indexPath.row]
        
        self.navigationController?.pushViewController(detailVC, animated: true)
        
    }
}


